import { Form } from '@ant-design/compatible';
import { DownOutlined, PlusOutlined ,QuestionCircleOutlined} from '@ant-design/icons';
import '@ant-design/compatible/assets/index.css';
import { Input, Modal,Table, Checkbox, InputNumber, Upload,Row,Tooltip, Switch, Button, Icon, Select, Radio, Card, Col, message } from 'antd';
import { formatMessage } from 'umi-plugin-react/locale';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import React, { useState } from 'react';
import { queryRule, updateRule, addRule, removeRule } from '../service';
import styles from '../style.less';
import router from 'umi/router';
// 导入自定义组件1
import PreviewForm from '@/components/PreviewForm';
import * as BdHelper from '@/utils/BdHelper';
import * as DataHelper from '@/helpers/DataHelper';
import * as TsxHelper from '@/helpers/TsxHelper';
import * as RequestHelper from '@/helpers/RequestHelper';
// 常量
const { TextArea } = Input;
const FormItem = Form.Item;

// 定义: 数据表单属性
interface DataFormProps extends FormComponentProps {
  // dataModalVisible: boolean;
  isUpdate: boolean
  dataFormValues: any
  common: any
}

/**
 * 添加节点
 * @param fields
 */
 const handleAdd = async (fields: any) => {
  return RequestHelper.bdExec({
    fn: addRule,
    args: fields,
    successMsg: formatMessage({ id: 'app.base.store-success' }),
    failMsg: formatMessage({ id: 'app.base.api-exception' }),
  });
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  return RequestHelper.bdExec({
    fn: updateRule,
    args: fields,
    successMsg: formatMessage({ id: 'app.base.update-success' }),
    failMsg: formatMessage({ id: 'app.base.api-exception' }),
  });
};
// 数据表单
const DataForm: React.FC<DataFormProps> = props => {
  // 组件属性
  const { form, common, handleName,nameList,isUpdate, dataFormValues } = props;

  // 图片状态
  const [picture, setPicture] = useState<any[]>([]);
  const [uploadChanged, setUploadChanged] = useState<boolean>(false);
  const [pictureLogo, setPictureLogo] = useState<any[]>([]);
  const [uploadLogoChanged, setUploadLogoChanged] = useState<boolean>(false);
  const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
  const [previewImg, setPreviewImg] = useState('');
 
  const imgList: any = [];
  const dtImgList: any = [];
  const rankChangeList: any = [];
  const handleChange = (value: any, option: any) => {
    let obj = {};
    let isSelect = true;
    option.map((item: any, index: any) => {
      if (value == item.key) {
        obj = item;
      }
    })
    let len = nameList.length;
    let coupon = [];
    console.log(coupon, 122)
    nameList.map((item: any, index: any) => {
      if (value == item.lang_code) {
        isSelect = false;
      }
      coupon.push({ lang_code: item.lang_code, title:item.title,content:item.content });
    })
    if (isSelect) {
      coupon.push({ lang_code: value, title:'',content:'' });
    }
    console.log(coupon, 332)
    handleName(coupon);
  }
  const columns = [
    {
      title: 'ISO Code',
      dataIndex: 'lang_code',
    },
    {
      title: (
        <>
          {formatMessage({ id: 'app.base.title' })}
          <Tooltip placement="top" title={'系统发送的欢迎信息的标题，不支持HTML，不超过75字节'}>
            <QuestionCircleOutlined style={{ marginLeft: 4 }} />
          </Tooltip>
        </>
      ),
      dataIndex: 'title',
      render: (text, record, index) => (
        <Input value={record.title} onChange={e => { rankChange(record, e.target.value, index) }} />
      )
    },
    {
      title: (
        <>
          {formatMessage({ id: 'app.base.content' })}
          <Tooltip placement="top" title={'请输入模板消息详细内容对应的变量。关键字个数需与已添加的模板一致。可以使用如下变量：{username}用户名 {sitename}站点名称 {groupname}用户组'}>
            <QuestionCircleOutlined style={{ marginLeft: 4 }} />
          </Tooltip>
        </>
      ),
      dataIndex: 'content',
      render: (text, record, index) => (
        <TextArea value={record.content} onChange={e => { rankChange1(record, e.target.value, index) }} />
      )
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record, index) => (
        <>
          <a
            onClick={() => {
              deletePic(record, index)
            }}
          >
            {formatMessage({ id: 'app.base.delete' })}
          </a>
        </>
      ),
    },
  ];
  const rankChange = (record, value, index) => {
    console.log(record, value)
    if (nameList.length > 0) {
      nameList.map((item, index) => {
        rankChangeList.push(item)
      })
    }
    rankChangeList[index].title = value ? value : '';
    console.log('rankChangeList', rankChangeList)
    handleName(rankChangeList);
  };
  const rankChange1 = (record, value, index) => {
    console.log(record, value)
    if (nameList.length > 0) {
      nameList.map((item, index) => {
        rankChangeList.push(item)
      })
    }
    rankChangeList[index].content = value ? value : '';
    console.log('rankChangeList', rankChangeList)
    handleName(rankChangeList);
  };
  const deletePic = (record: any, index2: any) => {
    if (nameList.length > 0) {
      nameList.map((item, index) => {
        dtImgList.push(item)
      })
    }
    dtImgList.splice(index2, 1);
    console.log('dtImgList', dtImgList)
    handleName(dtImgList);
    console.log('nameList', nameList)
  }
  //提交表单
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if (picture.length > 0) {
        fieldsValue.file_id = picture[0].file_id
        fieldsValue.file_url = picture[0].file_url
      }
      if(isUpdate){
        fieldsValue.id = dataFormValues.id;
      }
      fieldsValue.template = JSON.stringify(nameList);
      console.log("submit fields ", fieldsValue)
      if(fieldsValue.push_channel){
        fieldsValue.push_channel = fieldsValue.push_channel.join(',')
      }
      if(fieldsValue.push_disable){
        fieldsValue.push_disable = fieldsValue.push_disable.join(',')
      }
      const service = isUpdate ? handleUpdate(fieldsValue) : handleAdd(fieldsValue);
      // 如果更新成功之后，重置表单
      service.then((success: any) => {
        if (success) {
          message.success('保存成功')
          router.push('/system/notice-setting');
        }
      })

    });
  };

  // 设置上传文件值
  const setUploadFile = (fileList: any) => {
    setUploadChanged(true)
    let fileArr = DataHelper.getLastUploadFile(fileList)
    console.log("fileArr is ", fileArr)
    if (fileArr.length > 0) {
      setPicture(fileArr)
      setPreviewImg(fileArr[0].file_url)
    } else if (fileArr.length === 0) {
      console.log('set picture []')
      setPicture([])
    }
  }

  // 设置Logo上传文件值
  const setLogoUploadFile = (fileList: any) => {
    setUploadLogoChanged(true)
    let fileArr = DataHelper.getLastUploadFile(fileList)
    console.log("fileArr is ", fileArr)
    if (fileArr.length > 0) {
      setPictureLogo(fileArr)
      setPreviewImg(fileArr[0].file_url)
    } else if (fileArr.length === 0) {
      console.log('set picture []')
      setPictureLogo([])
    }
  }

  const parseData = (key: any, options: any) => {
    console.log(options);
    var name: any = "";
    if (Array.isArray(options) && options.length > 0) {
      options.map(item => {
        if (item.alias_key == key) {
          name = item?.item_value;
        }
      })
    }
    return name
  }

  // 初始化变量
  const token = BdHelper.getBdToken()

  // 编辑时初始化 picture
  const defaultPicture = DataHelper.buildFileByUrl(parseData('site_icon', dataFormValues))
  const defaultLogoPicture = DataHelper.buildFileByUrl(parseData('site_logo', dataFormValues))

  // 是否展示图片上传按钮
  const showUploadButton = DataHelper.showUploadBtn(isUpdate, picture, defaultPicture, uploadChanged)
  const showUploadLogoButton = DataHelper.showUploadBtn(isUpdate, pictureLogo, defaultLogoPicture, uploadLogoChanged)




  // 弹出框
  // @ts-ignore
  return <Card>
    <Col span={24}>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.use_name' })}>
        {form.getFieldDecorator('name', {
           initialValue: isUpdate ? dataFormValues.name : '',
          // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
        })(<Input placeholder={formatMessage({ id: 'app.base.please_input' })} />)}
      </FormItem>
    </Col>
    <Col span={24}>
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.type' })}>
      {form.getFieldDecorator('type', {
        initialValue: isUpdate ? dataFormValues.type?.toString() : '',
        //rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
      })(<Select placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
      {common.typeOption && TsxHelper.buildSelectOption(common.typeOption)}
    </Select>)}
    </FormItem>
    </Col>
    <Col span={24}>
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label='推送渠道' className={styles.check} help="若没勾选，则下面不显示对应的方式。若不能支持，则置灰不能勾选 。">
      {form.getFieldDecorator('push_channel', {
        initialValue: isUpdate ? dataFormValues.push_channel_arr:[],
        //rules: [{ required: true, message: '请选择！', }],
      })(<Checkbox.Group style={{ width: '100%' }} >
        <Row>
          <Row>
            {(common?.PushChannelOption && common?.PushChannelOption.length > 0) ? common?.PushChannelOption.map((item: any, index: any) => {
              return <Col span={4} >
                <Checkbox value={item.key?.toString()}>{item.name}</Checkbox>
              </Col>
            }) : ''
            }
          </Row>
        </Row>
      </Checkbox.Group>)}
    </FormItem>
    </Col>
    <Col span={24}>
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label='禁止推送渠道' className={styles.check}>
      {form.getFieldDecorator('push_disable', {
        initialValue: isUpdate ? dataFormValues.push_disable_arr:[],
        //rules: [{ required: true, message: '请选择！', }],
      })(<Checkbox.Group style={{ width: '100%' }} >
        <Row>
          <Row>
            {(common?.PushChannelOption && common?.PushChannelOption.length > 0) ? common?.PushChannelOption.map((item: any, index: any) => {
              return <Col span={4} >
                <Checkbox value={item.key?.toString()}>{item.name}</Checkbox>
              </Col>
            }) : ''
            }
          </Row>
        </Row>
      </Checkbox.Group>)}
    </FormItem>
    </Col>
    <Col span={24}>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.configuration_path' })}>
        {form.getFieldDecorator('config_path', {
           initialValue: isUpdate ? dataFormValues.config_path : '',
          // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
        })(<Input placeholder={formatMessage({ id: 'app.base.please_input' })} />)}
      </FormItem>
    </Col>
    <Col span={24}>
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.lang' })}>
      {form.getFieldDecorator('lang', {
        initialValue: isUpdate ? dataFormValues.lang?.toString() : undefined,
        //rules: [{ required: true, message: '请选择！', }],
      })(<Select onSelect={(e) => handleChange(e, common.multilingualoption)} placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
        {common.multilingualoption && TsxHelper.buildSelectOption(common.multilingualoption)}
      </Select>)}
    </FormItem>
    </Col>
    <Col span={24}>
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.name' })}>
      <Table
        columns={columns}
        dataSource={nameList}
        pagination={false}
      />
    </FormItem>
    </Col>
    <Col span={24}>
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.rank_num' })}>
      {form.getFieldDecorator('rank_num', {
        initialValue: isUpdate ? dataFormValues.rank_num : 888,
        rules: [],
      })(<InputNumber placeholder={formatMessage({ id: 'app.base.please_input' })} style={{ width: '100%' }} min={1}/>)}
    </FormItem>
    </Col>
    <Col span={24}>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.enabled_state' })}>
        {form.getFieldDecorator('is_enable', {
          initialValue: isUpdate ? dataFormValues.is_enable?.toString() : '',
          valuePropName: 'checked',
          // rules: [],
        })(<Switch checkedChildren={formatMessage({ id: 'app.base.is-enable.true' })} unCheckedChildren={formatMessage({ id: 'app.base.is-enable.close' })} />)}
      </FormItem>
    </Col>
    <Col span={24}>
      <div style={{ display: 'flex', justifyContent: 'center', marginTop: 24, }}>
        <Button type="primary" style={{ marginLeft: 30 }} onClick={okHandle} >保存</Button>
      </div>
    </Col>
    {
      previewModelVisible && (
        <PreviewForm
          previewModelVisible={previewModelVisible}
          onVisibleModel={handlePreviewModalVisible}
          previewImg={previewImg}
        />
      )
    }
  </Card>;
};

export default Form.create<DataFormProps>()(DataForm);
